package com.lolineet.auth.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.lolineet.auth.token.SysUsernamePasswordAuthToken;
import com.lolineet.auth.entity.SysUsernamePasswordLoginEntity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtTokenService
 *
 * @author YUKI.N
 * @version 1.0
 * @description
 * @date 2025/4/17 22:29
 */
@Data
@Component
public class JwtService {

    /**
     * JWT 加解密使用的密钥
     */

    @Value("${security.jwt.key}")
    private String key;


    /**
     * JWT Token 的有效时间(单位:秒)
     */
    @Value("${security.jwt.ttl}")
    private Integer ttl;


    public String createToken(Authentication authentication) {
        Map<String, Object> payload = new HashMap<>();
        if (authentication.getPrincipal() instanceof SysUsernamePasswordLoginEntity) {
            payload.put("type", "username");
        }
        Date now = new Date();
        Date expiration = DateUtil.offsetSecond(now, ttl);
        payload.put(JWTPayload.ISSUED_AT, now);
        payload.put(JWTPayload.EXPIRES_AT, expiration);
        payload.put(JWTPayload.SUBJECT, authentication.getName());
        payload.put(JWTPayload.JWT_ID, IdUtil.simpleUUID());

        return JWTUtil.createToken(payload, key.getBytes());
    }

    public static SysUsernamePasswordAuthToken getSysUsernamePasswordToken(String token) {
        return null;
    }

}
